//
//  AdressMangerVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2017/12/27.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "AdressMangerVC.h"
#import "AddressNoCell.h"
#import "AddressTwoCell.h"
#import "AddressOneCell.h"
#import "CreatNewAddressVC.h"
#import "AddressMangerAddView.h"

#import "AddressInfoModel.h"
@interface AdressMangerVC ()<AddressTwoCellDelegate>

@property (nonatomic, strong) NSMutableArray<AddressInfoModel *> *dataModels;

@property (nonatomic, weak) AddressMangerAddView *bottomView;


@property (nonatomic, weak) UIView *tableFooter;
@end

@implementation AdressMangerVC
//  urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

- (AddressMangerAddView *)bottomView{
    
    if (!_bottomView) {
        
        AddressMangerAddView *temp = (AddressMangerAddView *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([AddressMangerAddView class]) owner:nil options:nil].firstObject;
        
        CGFloat bottomViewH = IPhoneX ? 106 : 72;
        
        temp.frame = CGRectMake(0, KScreenH - bottomViewH, KScreenW, bottomViewH);
        
        _bottomView = temp;
        
        [self.view addSubview:temp];
        
    }
    
    return _bottomView;
}

- (UIView *)tableFooter{
    
    if (!_tableFooter) {
        CGFloat footerH = IPhoneX ? 106 : 72;
        UIView *temp = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, footerH)];
        
        _tableFooter = temp;
        
        self.groupTableView.tableFooterView = temp;
    }
    
    return _tableFooter;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"地址管理";
    
  
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.groupTableView.backgroundColor = viewBgGrey;
    
    self.tableFooter.backgroundColor = viewBgGrey;

    self.groupTableView.rowHeight = UITableViewAutomaticDimension;
    
    self.groupTableView.estimatedRowHeight = 100;
    
    [self.groupTableView registerNib:[UINib nibWithNibName:NSStringFromClass([AddressNoCell class]) bundle:nil] forCellReuseIdentifier:[AddressNoCell identifierStr]];
    
    [self.groupTableView registerNib:[UINib nibWithNibName:NSStringFromClass([AddressOneCell class]) bundle:nil] forCellReuseIdentifier:[AddressOneCell identifierStr]];
    
     [self.groupTableView registerNib:[UINib nibWithNibName:NSStringFromClass([AddressTwoCell class]) bundle:nil] forCellReuseIdentifier:[AddressTwoCell identifierStr]];
    
    MJWeakSelf
    self.groupTableView.mj_header = [XMGRefreshHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadData];
        
    }];
    
    [weakSelf.groupTableView.mj_header beginRefreshing];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadData) name:@"AddressDidAdd" object:nil];

  
}

/**
 * 获取会员收货地址列表
 * uid 会员id
 

 */

- (void)loadData{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    parameters[@"uid"] = myViewModel.user.uid;
    
   
    [[NetworkTools shareNetworkTools] sendRequestWithHttpMethod:GET_METHOD URLPath:@"Member/getMemberExpressAddress" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
MYJSONSTR
            
            
            self.dataModels = [AddressInfoModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            
            
            if (self.dataModels.count > 0) {
                
                self.bottomView.hidden = NO;
                
                CGFloat footerH = IPhoneX ? 106 : 72;
                
                self.tableFooter.height = footerH;
                
                
            }else{
                
                self.bottomView.hidden = YES;
                
                
                self.tableFooter.height = 0;
                
            }
            
            
            
            [self.groupTableView.mj_header endRefreshing];
            
            [self.groupTableView reloadData];
            
            
        }else{
            
            [self.groupTableView.mj_header endRefreshing];
            
            [SVProgressHUD showInfoWithStatus:error.domain];
        }
        
    }];
    
}





#pragma mark - tableviewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.dataModels == nil) {
        return  0;
    } else {
        
        if (self.dataModels.count == 0) {
            return  1;
        } else {
            return  self.dataModels.count;
        }
        
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.dataModels == nil) {
        return  0;
    } else {
        
        if (self.dataModels.count == 0) {
            return  1;
        } else {
            return  2;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        
        if (self.dataModels.count == 0) {
            
            AddressNoCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[AddressNoCell identifierStr]];
            
            
            
            return tableCell;
            
        } else {
            
            AddressOneCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[AddressOneCell identifierStr]];
            
            tableCell.model = self.dataModels[indexPath.section];
            
            return tableCell;
        }

        
    } else {
        
        AddressTwoCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[AddressTwoCell identifierStr]];
        
        tableCell.index = indexPath;
        
        tableCell.delegate = self;
        
        tableCell.model = self.dataModels[indexPath.section];
        
        return tableCell;
    }
    
    
    
}





- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (self.dataModels.count > 0) {
        return 10;
    } else {
        return 0.00001;
    }
    
  
    
}



- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    
    UIView *temp = [[UIView alloc]init];
    temp.backgroundColor = [UIColor whiteColor];
    return temp;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *temp = [[UIView alloc]init];
    temp.backgroundColor = viewBgGrey;
    return temp;
    
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.vc != nil) {
        
        self.vc.dataModel.selectAdress = self.dataModels[indexPath.section];
        
        [self.vc.tableView reloadData];

        [self.navigationController popViewControllerAnimated:YES];
        
    }

}

//@property (nonatomic, strong) NSString *province;
//
//@property (nonatomic, strong) NSString *city;
//
//@property (nonatomic, strong) NSString *districts;

//@property (nonatomic, strong) NSString *lastString;

- (void)editBtnDidClickWith:(NSIndexPath *)index{
    
//    [self.dataModels removeObjectAtIndex:index.section];
    CreatNewAddressVC *temp = [[CreatNewAddressVC alloc]init];
    
    AddressInfoModel *model = self.dataModels[index.section];
    
    temp.infoModel = model;
    
    temp.provinceId = model.province;
    
    temp.cityId = model.city;
    
    temp.districtId = model.district;
    
    temp.lastString = model.address_info;
    
    NSArray *arry = [model.address_info componentsSeparatedByString:@"-"];
    
    if (arry.count == 2) {
        
        temp.province = arry[0];
        
        temp.city = arry[1];
    } else {
        temp.province = arry[0];
        
        temp.city = arry[1];
        
        temp.districts = arry[2];
    }
    
    [self.navigationController pushViewController:temp animated:YES];
    
}



- (void)leftBtnDidTap:(NSIndexPath *)index{
    
    [self setDefaultAddress:index];
    
    for (AddressInfoModel *model in self.dataModels) {
        model.is_default = @"0";
    }
    
    self.dataModels[index.section].is_default = @"1";
    
    [self.groupTableView reloadData];
    
}


- (void)setDefaultAddress:(NSIndexPath *)index{
    
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    parameters[@"uid"] = myViewModel.user.uid;
    
    parameters[@"id"] = self.dataModels[index.section].addressID;
    
    NSLog(@"%@____++++++",parameters[@"id"]);
    
    
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Member/setDefaultExpressAddress" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            NSLog(@"%@",responseObject);
        }else{
            NSLog(@"%@",error);
            
        }
        
        
    }];
    
}


- (void)deleBtnDidClickWith:(NSIndexPath *)index{
    
  
    UIAlertController *contr = [UIAlertController alertControllerWithTitle:nil message:@"确定删除该地址吗?" preferredStyle:UIAlertControllerStyleAlert];
    
    MJWeakSelf;
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf deletAddressWithID:weakSelf.dataModels[index.section].addressID];
        
        [weakSelf.dataModels removeObjectAtIndex:index.section];
        
        if (weakSelf.dataModels.count > 0) {
            
            weakSelf.bottomView.hidden = NO;
            
            CGFloat footerH = IPhoneX ? 106 : 72;
            
            weakSelf.tableFooter.height = footerH;
            
            
        }else{
            
            weakSelf.bottomView.hidden = YES;
            
            
            weakSelf.tableFooter.height = 0;
            
        }
        
        
        [weakSelf.groupTableView reloadData];
        
        
    }];
    
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    
    [contr addAction:action2];
    
    [contr addAction:action1];
    
    [self presentViewController:contr animated:YES completion:nil];
    
   
}

- (void)deletAddressWithID:(NSString *)addressId{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    parameters[@"uid"] = myViewModel.user.uid;
    
    parameters[@"id"] = addressId;
    
    NSLog(@"%@",addressId);

    
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Member/memberAddressDelete" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            NSLog(@"%@",responseObject);
        }else{
            NSLog(@"%@",error);

        }
        
        
    }];
    
    
    
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
